<script setup lang="ts">
import { ref, Ref } from 'vue';
import { loginFn } from '../../api/user'
import { showToast } from 'vant'
import { useRouter } from 'vue-router';
import { useUserStore } from '../../stores/user'

const user = useUserStore()
const router = useRouter()
const loginname = ref('')
const password = ref('')

function onSubmit() {
  // console.log(loginname.value, password.value);
  loginFn({
    loginname: loginname.value,
    password: password.value
  }).then(res => {
    // 1. 登录成功
    // 2. 账号不存在
    // 3. 密码错误
    console.log(res);

    if (res.data.code == '200') {
      showToast({
        message: '登录成功'
      })
      router.push('/')
      /*
        还要通过全局状态将用户信息保留
      */

      // 1. 保存 token
      localStorage.setItem('token', res.data.data.token)
      // 2. 保存用户 id
      localStorage.setItem('userid', res.data.data.userid)
      // 3. 保存用户登录状态
      localStorage.setItem('loginState', 'true')

      // 在全局状态中保存用户的数据
      user.changeUserState({
        loginState: true,
        token: res.data.data.token,
        userid: res.data.data.userid
      })

    } else {
      showToast({
        message: res.data.message
      })
    }
  })
}
</script>
<template>
  <div class="box">
    <header class="header"> 登录 </header>
    <div class="content">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field v-model="loginname" name="用户名" label="用户名" placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]" />
          <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]" />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="danger" native-type="submit">
            登录
          </van-button>
        </div>
        <div style="margin: 16px;">
          <van-button @click="$router.push('/register/step1')" round block type="success">
            去注册
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<style scoped lang="scss">
.header {
  margin-bottom: 30px;
}
</style>
